package com.spera.genutil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;
import com.spera.exception.MyException;
import com.spring.nbrbt.tools.otherutil.SpringContextHolder;
import com.spring.security.core.context.AppContext;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.MD5Util;
import com.spring.security.core.util.UDate;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.Result;
import com.sso.api.web.dao.CFamilyMemberMapper;
import com.sso.api.web.model.CFamilyMember;

/**
 * @author wojunyu
 *
 */
public class TokenUtil {
	public static String USER_ID = "user_id";
	public static String USER_NAME = "user_name";
	public static String FAMILY_ID = "family_id";
	public static String ROLE_ID = "role_id";
	public static String MEMBER_NAME = "member_name";
	public static String DEPT_ID = "dept_id";
	public static String LOGIN_IP = "login_ip";
	public static String LOGIN_TIME = "login_time";
	public static String LOGIN_TYPE = "login_type";//customer ,teacher
	
	public static String CUS_LOGIN = "customer";
	public static String OA_LOGIN = "oa";
	public static String KIDS_PARK_ID = "kids_park_id";
	
	private static CFamilyMemberMapper cFamilyMemberMapper = SpringContextHolder.getBean(CFamilyMemberMapper.class);

	public static String SetSperaToken(JedisCache jedisCache,Token token,String type){
//		String user_uuid = ApplicationUtils.randomUUID();
		String user_uuid = SpUtil.getSessionId();
		Map<String,String> ms = Maps.newHashMap();
		if(StringUtils.isEmpty(token.getUser_id())||StringUtils.isEmpty(token.getUser_name())){
			return "";
		}
		ms.put(USER_ID, token.getUser_id());
		ms.put(USER_NAME, token.getUser_name());
		ms.put(LOGIN_TIME, UDate.dateToStr(new Date(), "yyyyMMddHHmmss"));
		ms.put(LOGIN_TYPE, type);
		
		if(ApplicationUtils.isNotNull(token.getFamily_id())){
			ms.put(FAMILY_ID, token.getFamily_id());
		}
		if(ApplicationUtils.isNotNull(token.getRole_id())){
			ms.put(ROLE_ID, token.getRole_id());
		}
		if(ApplicationUtils.isNotNull(token.getMember_name())){
			ms.put(MEMBER_NAME, token.getMember_name());
		}
		if(ApplicationUtils.isNotNull(token.getDept_id())){
			ms.put(DEPT_ID, token.getDept_id());
		}
		if(ApplicationUtils.isNotNull(token.getLogin_ip())){
			ms.put(LOGIN_IP, token.getLogin_ip());
		}
		if(ApplicationUtils.isNotNull(token.getKids_park_id())){
			ms.put(KIDS_PARK_ID, token.getKids_park_id());
		}
		jedisCache.hmset(user_uuid, ms);
		jedisCache.expire(user_uuid, JedisCont.JEDIS_EXPRISE);
		return user_uuid;
	}
	
	public static String SetSperaToken(JedisCache jedisCache,Token token,Integer sec,String type){
		String user_uuid = ApplicationUtils.randomUUID();
		Map<String,String> ms = Maps.newHashMap();
		if(StringUtils.isEmpty(token.getUser_id())||StringUtils.isEmpty(token.getUser_name())){
			return "";
		}
		ms.put(USER_ID, token.getUser_id());
		ms.put(USER_NAME, token.getUser_name());
		ms.put(LOGIN_TIME, UDate.dateToStr(new Date(), "yyyyMMddHHmmss"));
		ms.put(LOGIN_TYPE, type);
		
		if(ApplicationUtils.isNotNull(token.getFamily_id())){
			ms.put(FAMILY_ID, token.getFamily_id());
		}
		if(ApplicationUtils.isNotNull(token.getRole_id())){
			ms.put(ROLE_ID, token.getRole_id());
		}
		if(ApplicationUtils.isNotNull(token.getMember_name())){
			ms.put(MEMBER_NAME, token.getMember_name());
		}
		if(ApplicationUtils.isNotNull(token.getDept_id())){
			ms.put(DEPT_ID, token.getDept_id());
		}
		if(ApplicationUtils.isNotNull(token.getLogin_ip())){
			ms.put(LOGIN_IP, token.getLogin_ip());
		}
		if(ApplicationUtils.isNotNull(token.getKids_park_id())){
			ms.put(KIDS_PARK_ID, token.getKids_park_id());
		}
		jedisCache.hmset(user_uuid, ms);
		jedisCache.expire(user_uuid, sec);
		return user_uuid;
	}
	
	
	public static Map<String, Object> checkToken(String token,JedisCache jedisCache) {
		String isDevelopment = JedisCont.getProParm("isDevelopment");

		
		Map<String, Object> s = new HashMap<String, Object>();
		if (!ApplicationUtils.isNotNull(token)) {
			s.put(ApplicationUtils.STATUS, "-9999");
			s.put(ApplicationUtils.MSG, "请先登录");
			return s;
		} 
		if (!jedisCache.exists(token)) {
			s.put(ApplicationUtils.STATUS, "-9999");
			s.put(ApplicationUtils.MSG, "登录失效");
			return s;
		}
			String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
			
			if(!userType.equals("oa")){
				String phone=jedisCache.hget(token,TokenUtil.USER_NAME);
				String userID=jedisCache.hget(token,TokenUtil.USER_ID);
				
				Map<String,Object> param=new HashMap<String,Object>();
				param.put("c_user_id", userID);

				CFamilyMember cFamilyMember=cFamilyMemberMapper.selectByPrimaryKey(userID);

				if(!cFamilyMember.getPhone().equals(phone)){
					jedisCache.del(token);
					s.put(ApplicationUtils.STATUS, "-9999");
					s.put(ApplicationUtils.MSG, "用户登录已失效，请先重新登录");
					return s;
				}
			}
				//刷新token
				if(isDevelopment.equals("1")){
					jedisCache.expire(token, 500000000);
				}else{
					jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
				}
				return null;
			
		
	}
	
	public static Result checkTokenNew(String token,JedisCache jedisCache) {
		Result s = new Result();
		if (!ApplicationUtils.isNotNull(token)) {
			s.setStatus("0");
			s.setMsg("请先登录");
			return s;
		} else {
			if (!jedisCache.exists(token)) {
				s.setStatus("-9999");
				s.setMsg("用户登录已失效，请先重新登录");
				return s;
			}
			else{
				//刷新token
				String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
				
				if(!userType.equals("oa")){
					String phone=jedisCache.hget(token,TokenUtil.USER_NAME);
					String userID=jedisCache.hget(token,TokenUtil.USER_ID);
					
					Map<String,Object> param=new HashMap<String,Object>();
					param.put("c_user_id", userID);

					CFamilyMember cFamilyMember=cFamilyMemberMapper.selectByPrimaryKey(userID);

					if(!cFamilyMember.getPhone().equals(phone)){
						jedisCache.del(token);
						s.setStatus("-9999");
						s.setMsg("用户登录已失效，请先重新登录");
						return s;
					}
				}
				
				
				String isDevelopment = JedisCont.getProParm("isDevelopment");
				if(isDevelopment.equals("1")){
					jedisCache.expire(token, 500000000);
				}else{
					jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
				}
				return null;
			}
		}
	}
	
	public static BaseResult checkTokenBR(String token,JedisCache jedisCache) {
		BaseResult br = new BaseResult();
		if (!ApplicationUtils.isNotNull(token)) {
			br.setStatus("-9999");
			br.setMsg("请先登录");
			return br;
		} else {
			if (!jedisCache.exists(token)) {
				br.setStatus("-9999");
				br.setMsg("用户登录已失效，请先重新登录");
				return br;
			}
			else{
				//刷新token
				//jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
				String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
				
				if(!userType.equals("oa")){
					String phone=jedisCache.hget(token,TokenUtil.USER_NAME);
					String userID=jedisCache.hget(token,TokenUtil.USER_ID);
					
					Map<String,Object> param=new HashMap<String,Object>();
					param.put("c_user_id", userID);

					CFamilyMember cFamilyMember=cFamilyMemberMapper.selectByPrimaryKey(userID);

					if(!cFamilyMember.getPhone().equals(phone)){
						jedisCache.del(token);
						br.setStatus("-9999");
						br.setMsg("用户登录已失效，请先重新登录");
						return br;
					}
				}
				
				
				String isDevelopment = JedisCont.getProParm("isDevelopment");
				if(isDevelopment.equals("1")){
					jedisCache.expire(token, 500000000);
				}else{
					jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
				}
				return null;
			}
		}
	}
	
	public static void checkTokenThrowException(String token,JedisCache jedisCache) throws Exception{
		if (!ApplicationUtils.isNotNull(token)) {
			throw new MyException("-9999","请先登录");
		} else {
			if (!jedisCache.exists(token)) {
				throw new MyException("-9999","用户登录已失效，请先重新登录");
			}
			else{
				String userType=jedisCache.hget(token,TokenUtil.LOGIN_TYPE);
			
				if(!userType.equals("oa")){
					String phone=jedisCache.hget(token,TokenUtil.USER_NAME);
					String userID=jedisCache.hget(token,TokenUtil.USER_ID);
					
					Map<String,Object> param=new HashMap<String,Object>();
					param.put("c_user_id", userID);

					CFamilyMember cFamilyMember=cFamilyMemberMapper.selectByPrimaryKey(userID);

					if(!cFamilyMember.getPhone().equals(phone)){
						jedisCache.del(token);
						throw new MyException("-9999","用户登录已失效，请先重新登录");
					}
				}
				String isDevelopment = JedisCont.getProParm("isDevelopment");
				if(isDevelopment.equals("1")){
					jedisCache.expire(token, 500000000);
				}else{
					jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
				}
			}
		}
	}
	
	/**
	 * 无token的接口增加权限判断
	 * @param timestamp 时间戳除以1000
	 * @param hashcode  时间戳加密钥再MD5加密
	 * @return
	 */
	public static BaseResult checkApi(Long timestamp,Long hashcode){
		BaseResult ret = new BaseResult();
		long defTime = new Date().getTime()/1000-timestamp;
    	if(defTime>3000){
    		ret.setStatus("0");
    		ret.setMsg("无权调用此接口");
    	}else if(!hashcode.equals(MD5Util.string2MD5(timestamp+AppContext.TIMESTAMPCONTEXT))){
    		ret.setStatus("0");
    		ret.setMsg("无权调用此接口");
    	}
    	return ret;
	}
}
